package com.htht.job.admin.core.shiro;


import com.alibaba.fastjson.JSON;
import com.htht.job.admin.core.util.MD5Utils;
import com.htht.job.core.api.DubboShiroService;
import com.htht.job.executor.model.shiro.Resource;
import com.htht.job.executor.model.shiro.Role;
import com.htht.job.executor.model.shiro.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jws.soap.SOAPBinding;
import java.util.HashSet;
import java.util.Set;
@Component
public class UpmsRealm extends AuthorizingRealm {

    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "123456";
    @Autowired
    private DubboShiroService dubboShiroService;
    /*
       * 授权
       */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String dbUserString =dubboShiroService.findByUserName(user.getUserName());
        User dbUser=JSON.parseObject(dbUserString,User.class);
        Set<String> roleNames = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();
        Set<Role> roles = dbUser.getRoles();
        for (Role role : roles) {
            Set<Resource> resources = role.getResources();
            for (Resource resource : resources) {
                    permissions.add(resource.getSourceKey());

            }
            roleNames.add(role.getRoleKey());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }

    /*
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        String username = (String) authcToken.getPrincipal();

        String userString = dubboShiroService.findByUserName(username);
        User user= JSON.parseObject(userString, User.class);
        String password = new String((char[]) authcToken.getCredentials());

        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        // 密码错误
        if (!MD5Utils.md5(password).equals(user.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        // 账号锁定
        if (user.getLocked() == 1) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());

        return info;
    }
}
